package com.example.routelink.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.net.Ipv4Util;
import com.alibaba.fastjson2.JSON;
import com.example.routelink.gateway.entity.ResultData;
import com.example.routelink.gateway.entity.ResultEnum;
import com.example.routelink.gateway.utils.IpUtils;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.util.SubnetUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class BlacklistFilterGatewayFilterFactory extends BaseFilter<BlacklistFilterGatewayFilterFactory.Config> implements Ordered {
    public BlacklistFilterGatewayFilterFactory() {
        super(BlacklistFilterGatewayFilterFactory.Config.class);
    }

    public static List<String> ipList = new ArrayList<>();

    private List<String> subnetMaskList = new ArrayList<>();

    private final String filterName = "黑名单";

    @PostConstruct
    private void init() {
        ipList = FileUtil.readUtf8Lines(System.getProperty("user.dir") + "\\config\\blacklist.txt");
        subnetMaskList = FileUtil.readUtf8Lines(System.getProperty("user.dir") + "\\config\\blackSubnetMaskList.txt");
    }

    @Override
    public GatewayFilter apply(BlacklistFilterGatewayFilterFactory.Config config) {
        return (exchange, chain) -> {
            long startTime = System.currentTimeMillis();
            String ip = IpUtils.getRealIpAddress(exchange.getRequest());
            if (!Validator.isIpv4(ip)) {
                writeLog(filterName, startTime, "校验失败,非 ipv4地址，用户IP是 {} ", ip);
                return response(exchange, ResultEnum.ErrBlackList);
            }
            if (CollUtil.isNotEmpty(ipList) && CollUtil.contains(ipList, ip)) {
                writeLog(filterName, startTime, "校验失败,非 ipv4地址，用户IP是 {} ", ip);
                return response(exchange, ResultEnum.ErrBlackList);
            }
            if (CollUtil.isNotEmpty(subnetMaskList)) {
                for (String subnetMask : subnetMaskList) {
                    SubnetUtils utils = new SubnetUtils(subnetMask);
                    SubnetUtils.SubnetInfo info = utils.getInfo();
                    if (info.isInRange(ip)) {
                        writeLog(filterName, startTime, "校验失败,用户IP是 {} ,匹配到黑名单网段 {} ", ip, subnetMask);
                        return response(exchange, ResultEnum.ErrBlackList);
                    }
                }
            }
            writeLog(filterName, startTime, "校验通过,用户IP是 {}  ", ip);
            return chain.filter(exchange);
        };
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Data
    public static class Config {

    }
}
